<template>
    <div :style="carStyle" @mouseover="hoverCard = true" @mouseout="hoverCard = false">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <!-- <button class="btn_dashed" @click="dialogFormVisible = true">查&nbsp;询</button> -->
            <i v-if="!isEdit && hoverCard" @click.prevent="cardFullScreen" class="cardfullScreen iconfont icon-quanping"
                @mousemove="hoverCard = true"></i>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts-gl';
// import { cardDataLoad, boardLoad } from '@/api/share'

export default {
    name: "Grid3D",
    components: {
        echarts
    },
    props: {
        obj: Object,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        setIndex: Function,
        gotoUrl: {
            type: Function,
            default: function () { }
        }
    },
    data() {
        return {
            showContent: false,
            titleStyle: {},
            chart: undefined,
            carStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            isFullScreen: false,
            dataStr: "",
            timer: "",
            filterForm: {
                pageInfo: {
                    pageSize: 999,
                    page: 1,
                    totalCount: 0
                },
                tableId: 0,
                structureIds: [],
                beginTime: undefined,
                endTime: undefined,
                sortType: "1",
                dateTime: "",
            },
            seriesData: [],
            hoverCard: false,
        }
    },
    beforeDestroy() {
        clearInterval(this.timer)
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null;
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            // self.chart.resize();
            self.setStyle();
        }, true);
    },
    methods: {
        setStyle() {
            if (this.isFullScreen) return false;
            var self = this;
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";
            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            }

            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }

            if (this.chart) {
                this.$nextTick(() => {
                    this.chart.resize({
                        width: style.width,
                        height: style.height,
                    });
                });
            }
        },
        reloadInfo() {
            // 重绘
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            clearInterval(this.timer);

            // #region
            const end = new Date();
            const start = new Date();

            // #*********# 硬件表不读取缓存 / 非硬件表默认读取缓存
            // 缓存读取数据
            if (this.obj.tableData.type == 0) {
                this.filterForm.isOnlie = true;

                // 查询一天内数据
                start.setTime(start.getTime() - 3600 * 1000 * 24);
                this.filterForm.beginTime = this.parseTime(start);
                this.filterForm.endTime = this.parseTime(end);
            } else {
                this.filterForm.isOnlie = false;

                start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
                this.filterForm.beginTime = this.parseTime(start, "{y}-{m}-{d}");
                this.filterForm.endTime = this.parseTime(end);
            }
            // #endregion

            // 第一次请求
            this.getLineData((dataResult) => {
                this.resultDataToObject(dataResult);
                this.setOptions();

                // 循环刷新
                this.timedRefresh();
            });
        },
        // 数据转换
        resultDataToObject(dataResult) {
            var serveData = [];
            if (dataResult.dataList && dataResult.columns) {
                dataResult.dataList.forEach((data, j) => {
                    this.obj.tableData.barList.forEach((e, index) => {
                        if (!serveData[index]) {
                            serveData.push([]);
                        }
                        serveData[index].push([data[(index * 3) + 0], data[(index * 3) + 1], data[(index * 3) + 2]]);
                    });
                });
            }
            this.seriesData = serveData;
        },
        // 定时刷新
        timedRefresh() {
            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            // 刷新时间兼容处理
            if (this.obj.tableData.type == 1 && timeSize < 60) {
                timeSize = 60;
            }

            if (this.isReload) {
                this.timer = setInterval(() => {
                    const end = new Date();
                    this.filterForm.endTime = this.parseTime(end, "{y}-{m}-{d} {h}:{i}:{s}");

                    this.getLineData((dataResult) => {
                        this.resultDataToObject(dataResult);
                        this.setOptions();
                    });
                }, timeSize * 1000);
            }
        },
        getLineData(callback) {

            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;

                this.seriesData = [
                    [
                        [
                            1,
                            3,
                            1,
                        ],
                        [
                            2,
                            3,
                            2,
                        ],
                        [
                            3,
                            3,
                            5,
                        ]
                        ,
                        [
                            4,
                            3,
                            6,
                        ]
                        ,
                        [
                            5,
                            3,
                            8,
                        ]
                        ,
                        [
                            6,
                            3,
                            7,
                        ]
                        ,
                        [
                            7,
                            3,
                            7,
                        ]
                    ]
                ]
                this.setOptions();
                return false;
            }
            // #endregion

            // #region 参数不完整
            var idlist = [];
            for (var i = 0; i < this.obj.tableData.barList.length; i++) {
                var e = this.obj.tableData.barList[i];

                if (e.xLineId && e.yLineId && e.zLineId) {
                    idlist.push(e.xLineId);
                    idlist.push(e.yLineId);
                    idlist.push(e.zLineId);
                } else {
                    idlist = [];
                    break;
                }
            };
            if (idlist.length < this.obj.tableData.barList.length) {
                this.showContent = false;
                return false;
            }
            // #endregion

            this.showContent = true;

            this.filterForm.tableId = this.obj.tableData.tableId;
            this.filterForm.pageInfo.pageSize = this.obj.tableData.count;
            this.filterForm.structureIds = idlist;
            if (this.obj.tableData.type != 1) {
                cardDataLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            } else {
                boardLoad(this.filterForm).then((res) => {
                    if (res.data.code == 0) {
                        if (callback) {
                            callback(res.data.data.dataResult);
                        }
                    } else {
                        console.error(res.data.message)
                    }
                }).catch(() => {
                    clearInterval(this.timer)
                });
            }
        },
        setOptions() {
            var self = this;
            var seriesData = [];

            console.log(this.seriesData);

            // let expectedData = this.xData;
            // let columns = this.yColumns;
            // let actualData = this.seriesData;

            if (!this.seriesData.length) {
                this.chart.clear();
                return false;
            }

            // 颜色相关
            var color = "#333333";
            if (this.obj.tableData.color) {
                color = this.obj.tableData.color;
            }
            var lineColor = "#bbbbbb"
            if (this.obj.tableData.lineColor) {
                lineColor = this.obj.tableData.lineColor;
            }
            var lineWidth = this.obj.tableData.lineWidth;
            var xycName = [this.obj.tableData.xAxisName, this.obj.tableData.yAxisName, this.obj.tableData.zAxisName];
            var newColors = [];
            this.obj.tableData.barList.forEach(e => {
                if (e.lineColor) {
                    newColors.push(e.lineColor);
                }
            });
            var showGrid = true;
            if (!this.obj.tableData.isShowGrid) {
                showGrid = this.obj.tableData.isShowGrid;
            }

            this.seriesData.forEach((e, index) => {
                seriesData.push({
                    type: 'line3D',
                    name: this.obj.tableData.barList[index].name,
                    lineStyle: {
                        width: lineWidth,
                    },
                    data: e,
                    // animation: true,
                    // animationDurationUpdate: 1000,
                    // animationEasingUpdate: 'cubicOut',
                })
            })

            // console.log(seriesData);

            this.chart.setOption({
                tooltip: {
                    backgroundColor: "rgba(0,0,0, .7)",
                    textStyle: {
                        color: "#ffffff"
                    },
                    formatter: function (param) {
                        // console.log(param)
                        return `${param.seriesName}<br>
                                ${xycName[0]}：${param.data[0]}<br>
                                ${xycName[1]}：${param.data[1]}<br>
                                ${xycName[2]}：${param.data[2]}<br> `
                    }
                },
                color: newColors,
                grid3D: {
                    show: true,
                    boxWidth: 200,
                    boxHeight: 100,
                    boxDepth: 100,
                    axisLine: {
                        lineStyle: {
                            color: color,
                        },
                    },
                    axisLabel: {
                        show: true,
                        textStyl: {
                            color: color,
                        },
                    },
                    axisPointer: {
                        show: true,
                        label: {
                            show: true,
                        }
                    },
                    splitLine: {
                        show: showGrid,
                        lineStyle: {
                            color: lineColor,
                        },
                    },
                    viewControl: {
                        distance: 250,
                        alpha: 10,
                        beta: 30,
                        animation: true,
                    },
                },
                // 三维坐标轴
                xAxis3D: {
                    type: 'value',
                    name: xycName[0],
                    min: this.obj.tableData.fwData[0].min,
                    max: this.obj.tableData.fwData[0].max,
                },
                yAxis3D: {
                    type: 'value',
                    name: xycName[1],
                    min: this.obj.tableData.fwData[1].min,
                    max: this.obj.tableData.fwData[1].max,
                },
                zAxis3D: {
                    type: 'value',
                    name: xycName[2],
                    min: this.obj.tableData.fwData[2].min,
                    max: this.obj.tableData.fwData[2].max,
                },
                series: seriesData,
            });
        },
        cardFullScreen() {
            if (this.isFullScreen) {
                this.isFullScreen = false;
                this.setStyle();
            } else {
                this.carStyle.top = 0;
                this.carStyle.left = 0;
                this.carStyle.right = 0;
                // this.carStyle.zIndex = 666;
                this.carStyle.bottom = 0;
                this.carStyle.position = 'fixed';
                this.canvasStyle.width = "100%";
                this.canvasStyle.height = "100%";
                if (!this.carStyle.backgroundColor || this.carStyle.backgroundColor == 'rgba(0, 0, 0, 0)') {
                    this.carStyle.backgroundColor = "#04142b";
                }
                // this.chart.resize({
                //     width: "100%",
                //     height: "100%",
                // });

                this.$nextTick(() => {
                    // this.chart.resize();
                    this.chart.resize({
                        width: document.body.clientWidth + "px",
                        height: document.body.clientHeight + "px",
                    });
                })

                this.isFullScreen = true;
            }

            this.$emit('setIndex')
        },
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);
                    this.reloadInfo();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>

<style></style>